package com.cskaoyan.market.service;

import com.cskaoyan.market.db.domain.MarketCart;
import com.cskaoyan.market.db.domain.MarketCartExample;
import com.cskaoyan.market.db.domain.MarketGoodsProduct;
import com.cskaoyan.market.db.mapper.MarketCartMapper;
import com.cskaoyan.market.db.mapper.MarketGoodsProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: 付诚
 * @Date: 2024/5/21 19:30
 * @Description:
 */
@Service
public class WxCartServiceImpl implements WxCartService {
    @Autowired
    private MarketCartMapper marketCartMapper;
    @Autowired
    private MarketGoodsProductMapper marketGoodsProductMapper;

    @Override
    public Integer update(Integer goodsId, Integer id, Integer number, Integer productId) {
        // 购物车物品数量最低为1
        if (number < 1) {
            number = 1;
        }


        MarketGoodsProduct marketGoodsProduct = marketGoodsProductMapper.selectByPrimaryKey(productId);
        // 判断库存数量
        if (marketGoodsProduct.getNumber() < number) {
            // 库存不足
            return -1;
        }


        MarketCart marketCart = marketCartMapper.selectByPrimaryKey(id);
        marketCart.setNumber(number.shortValue());
        marketCart.setUpdateTime(LocalDateTime.now());
        marketCartMapper.updateByExample(marketCart, null);
        return 1;
    }

    @Override
    public Map<String, Object> delete(Map<String, List<Integer>> prodectIds) {
        Map<String, Object> data = new HashMap<>();

        // 删除购物车商品
        MarketCartExample marketCartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
        criteria.andLogicalDeleted(false);
        criteria.andProductIdIn(prodectIds.get("productIds"));

        marketCartMapper.deleteByExample(marketCartExample);

        // 返回响应数据
        data.put("checkedGoodsAmount",0);
        data.put("checkedGoodsCount",0);
        data.put("goodsAmount",0);
        data.put("goodsCount",0);
        return data;
    }
}
